package com.banzhi.shop.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.entity.findallgoods.Goods_Data;
import com.banzhi.shop.model.CallBack.FindAllGoodsCallBack;
import com.banzhi.shop.model.CallBack.HomeFrgModelCallBack;
import com.banzhi.shop.model.CallBack.ISCanByCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;
import com.banzhi.shop.model.IFindAllGoodsModel;
import com.banzhi.shop.model.IHomeFrgModel;
import com.banzhi.shop.model.IIsCanByModel;
import com.banzhi.shop.model.Impl.FindAllGoodsImpl;
import com.banzhi.shop.model.Impl.HomeFrgModelImpl;
import com.banzhi.shop.model.Impl.IsCanByImpl;
import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.CustomToast;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.banzhi.shop.R.id.srlayout;
//搜索商品
public class FindAllGoodsActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener,
        FindAllGoodsCallBack, HomeFrgModelCallBack, WXshareCallBack, ISCanByCallBack {
    private ImageView ivback;
    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout srllistview;
    private int page = 1;
    private RelativeLayout rlnodata;
    private EditText etfind;
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private IFindAllGoodsModel model;
    private List<Goods_Data> goods_datas = new ArrayList<>();
    private CommonHeadAdapter<Goods_Data> adapter;
    private IHomeFrgModel homeFrgModel;
    private int positon;
    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private WXshareModel wxmodel;
    private IIsCanByModel canByModel;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_all_goods);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new FindAllGoodsImpl();
        homeFrgModel = new HomeFrgModelImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);
        wxmodel = new WXshareImpl();
        canByModel = new IsCanByImpl();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        srllistview = (SwipeRefreshLayout) findViewById(srlayout);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
        etfind = (EditText) findViewById(R.id.et_find);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        srllistview.setOnRefreshListener(this);
        etfind.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    page = 1;
                    model.getData(page, etfind.getText().toString().trim(), FindAllGoodsActivity.this);
                } else {
                    model.getData(page, FindAllGoodsActivity.this);
                }
            }
        });
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                if (etfind.getText().length() == 0) {
                    LoadingDialogUtils.showProgress(FindAllGoodsActivity.this, "正在加载,请稍后~");
                    model.getData(page, FindAllGoodsActivity.this);
                } else {
                    LoadingDialogUtils.showProgress(FindAllGoodsActivity.this, "正在加载,请稍后~");
                    model.getData(page, etfind.getText().toString().trim(), FindAllGoodsActivity.this);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        if (etfind.getText().length() == 0) {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getData(page, FindAllGoodsActivity.this);
        } else {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getData(page, etfind.getText().toString().trim(), FindAllGoodsActivity.this);
        }
    }

    /**
     * @param object 获取数据成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        List<Goods_Data> datas = (List<Goods_Data>) object;
        if (page == 1) {
            goods_datas.clear();
        } else {
            if (datas.size() == 0) {
                return;
            }
        }
        goods_datas.addAll(datas);
        if (goods_datas.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        if (adapter == null) {
            adapter = new CommonHeadAdapter<Goods_Data>(this, R.layout.recycleview_items2, goods_datas) {
                @Override
                public void convert(ViewHolder holder, final Goods_Data data, final int position) {
                    //标题
                    holder.setText(R.id.tv_home_content, data.getTitle());
                    //库存
                    holder.setText(R.id.tv_kucun, data.getTotal());
                    //价格
                    if (data.getBegin_price().equals(data.getEnd_price())) {
                        holder.getView(R.id.ll_endprice).setVisibility(View.GONE);
                        if (ASUtils.isCanUse(data.getMarketprice())) {
                            holder.setText(R.id.tv_price, data.getMarketprice());
                        }
                    } else {
                        holder.getView(R.id.ll_endprice).setVisibility(View.VISIBLE);
                        if (ASUtils.isCanUse(data.getBegin_price())) {
                            holder.setText(R.id.tv_price, data.getBegin_price());
                        }
                        if (ASUtils.isCanUse(data.getEnd_price())) {
                            holder.setText(R.id.tv_endprice, data.getEnd_price());
                        }
                    }
                    //图片
                    if (ASUtils.isCanUse(data.getThumb())) {
                        Picasso.with(MyApp.context).load(data.getThumb()).placeholder(R.mipmap.zhanweitu2).into(holder.getImageView(R.id.img_home));
                    }
                    if ("1".equals(data.getIsagentgoods())) {                             //店长专区
                        holder.getView(R.id.ll_lirun).setVisibility(View.GONE);
                        holder.getView(R.id.ll_zaisou).setVisibility(View.GONE);
                        holder.getView(R.id.iv_add_dianpu).setVisibility(View.GONE);
                        holder.getView(R.id.iv_add_image).setVisibility(View.GONE);
                        holder.getView(R.id.iv_fenxiang).setVisibility(View.GONE);
                    } else {                                                              //非店主专区
                        holder.getView(R.id.ll_lirun).setVisibility(View.VISIBLE);
                        holder.getView(R.id.ll_zaisou).setVisibility(View.VISIBLE);
                        holder.getView(R.id.iv_add_dianpu).setVisibility(View.VISIBLE);
                        holder.getView(R.id.iv_add_image).setVisibility(View.VISIBLE);
                        holder.getView(R.id.iv_fenxiang).setVisibility(View.VISIBLE);

                        //利润
                        if (ASUtils.isCanUse(data.getProfit())) {
                            holder.setText(R.id.tv_liyun, NumberUtils.DecimalFormat(data.getProfit()));
                        }
                        //在售人数
                        holder.setText(R.id.tv_Peoplenum, data.getSharebtn());
                        if ("0".equals(data.getIcon())) {
                            holder.getImageView(R.id.iv_add_dianpu).setImageResource(R.mipmap.jian1);
                        } else if ("1".equals(data.getIcon())) {
                            holder.getImageView(R.id.iv_add_dianpu).setImageResource(R.mipmap.jia1);
                        }
                        holder.getImageView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                FindAllGoodsActivity.this.positon = position;
                                if ("0".equals(data.getIcon())) {
                                    homeFrgModel.deleteGoods(data.getId(), null, FindAllGoodsActivity.this);
                                } else if ("1".equals(data.getIcon())) {
                                    homeFrgModel.AddDianpu(data.getId(), FindAllGoodsActivity.this);
                                }

                        }
                    });
                    holder.getImageView(R.id.iv_add_image).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(FindAllGoodsActivity.this, CommodityDetailsActivity.class);
                            intent.putExtra("id", data.getId());
                            intent.putExtra("type", "1");
                            startActivity(intent);
                        }
                    });
                    holder.getImageView(R.id.iv_fenxiang).setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                wxURL = null;
                                FindAllGoodsActivity.this.positon = position;
                                showSharePopupwindow(data);
                            }
                        });
                    }


                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setOnItemClickListener(new CommonHeadAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                canByModel.getData(goods_datas.get(position).getId(), FindAllGoodsActivity.this);
                FindAllGoodsActivity.this.position = position;

            }
        });
    }

    /**
     * @param object 获取数据失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void getDataSuccess(Object object) {

    }

    @Override
    public void getDataError(Object object) {

    }

    /**
     * @param object 添加到店铺成功
     */
    @Override
    public void AddDianpuSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "上架成功", jsonObject.optString("res"));
//        ToastUtils.makeToastShort("添加到店铺成功");
        if ("0".equals(goods_datas.get(positon).getIcon())) {
            goods_datas.get(positon).setIcon("1");
        } else {
            goods_datas.get(positon).setIcon("0");
        }
        adapter.notifyItemChanged(positon);
    }

    /**
     * @param object 添加到店铺失败
     */
    @Override
    public void AddDianpuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 删除成功
     */
    @Override
    public void deleteSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "下架成功", jsonObject.optString("res"));
        if ("0".equals(goods_datas.get(positon).getIcon())) {
            goods_datas.get(positon).setIcon("1");
        } else {
            goods_datas.get(positon).setIcon("0");
        }
        adapter.notifyItemChanged(positon);
    }

    /**
     * @param object 删除失败
     */
    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(this, wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima3(this, goods_datas.get(positon).getTitle(), goods_datas.get(positon).getMarketprice(), null, null, null, goods_datas.get(positon).getThumb(), wxURL);
        } else if (num == WEIXINHAOYOU) {
          //  ShareUtils.wxshare(goods_datas.get(positon).getTitle(), goods_datas.get(positon).getThumb_url().get(0), "加入半职，和崔万志一起创业", wxURL);
            ShareUtils.wxshare(goods_datas.get(positon).getTitle(),goods_datas.get(positon).getImages().get(0), "加入半职，和崔万志一起创业", wxURL);
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(goods_datas.get(positon).getTitle(), goods_datas.get(positon).getThumb(), wxURL);
        }
    }

    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 展示分享的popupwindow
     */
    private void showSharePopupwindow(final Goods_Data data) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (data != null) {
            tvprice.setText(NumberUtils.DecimalFormat(data.getProfit()));
            tvpricetwo.setText(NumberUtils.DecimalFormat(data.getProfit()));
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(FindAllGoodsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, LIANJIE, FindAllGoodsActivity.this);
                    } else {
                        ShareUtils.copyLianjie(FindAllGoodsActivity.this, wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(FindAllGoodsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, ERWEIMA, FindAllGoodsActivity.this);
                    } else {
                        ShareUtils.ereima3(FindAllGoodsActivity.this, data.getTitle(), data.getMarketprice(), null, null, null, data.getThumb(), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(FindAllGoodsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, WEIXINHAOYOU, FindAllGoodsActivity.this);
                    } else {
                        ShareUtils.wxshare(data.getTitle(), data.getImages().get(0), "加入半职，和崔万志一起创业", wxURL);
                    //    ShareUtils.wxshare(data.getTitle(), data.getThumb_url().get(0), "加入半职，和崔万志一起创业", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(FindAllGoodsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, PENGYOUQUAN, FindAllGoodsActivity.this);
                    } else {
                        ShareUtils.wxPengyouquan(data.getTitle(), data.getThumb(), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    @Override
    public void getCanBuySuccess(Object object) {
        Intent intent = null;
        if ("1".equals(goods_datas.get(position).getIsagentgoods())) {
            intent = new Intent(FindAllGoodsActivity.this, CommodityDetails_DZZQActivity.class);
        } else {
            intent = new Intent(FindAllGoodsActivity.this, CommodityDetailsActivity.class);
        }
        intent.putExtra("id", goods_datas.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void getCanBuyError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
